#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2025 粤港澳大湾区（广东）国创中心

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

File: PythonMeshDlg.py
Desc: Dialog for mesh settings in the application.
Author: xumanjia
Date: 2025-08-01
"""
import os
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QDialog, QMessageBox
from PyQt5 import uic
from PyQt5.QtCore import Qt, pyqtSignal
from Pub.configLoad import global_scope
from Dialog.PythonPreviewDlg import PreviewLabel

class MeshSettingView(QDialog):
    """运行时加载UI文件的弹窗"""
    closePreview = pyqtSignal()
    def __init__(self, args, parent=None):
        super().__init__(parent)
        global  global_scope
        self.doc = global_scope["doc"]
        self.NCTI = global_scope["NCTI"]

        self.args = args
        # self.sel = args['sel']
        base_dir = os.path.dirname(os.path.abspath(__file__)) + "\\ui\\"
        ui_path = os.path.join(base_dir, "MeshSettingView.ui")

        if not os.path.exists(ui_path):
            print(f"错误: UI文件不存在 - {ui_path}")
            sys.exit(1)

        uic.loadUi(ui_path, self)
        
        # 设置窗口属性
        self.setWindowTitle("网格设置")
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)

        # 连接信号槽
        self.connect_signals()

        #初始化数据
        self.init_data()

    
    def connect_signals(self):
        self.btn_ok.clicked.connect(self.on_ok_clicked)
        self.pb_select.clicked.connect(self.on_select_clicked)
        self.btn_cancel.clicked.connect(self.on_cancel_clicked)

    def init_data(self):
        if "网格命令" not in self.args: 
            QMessageBox.warning(self, "输入错误", "请填写网格命令字段！")
            return

        if "网格尺寸" in self.args:
            self.le_size.setText(str(self.args["网格尺寸"]))
        else:
            QMessageBox.warning(self, "输入错误", "请填写网格尺寸字段！")
            return
        
        if "网格类型" in self.args:
            self.cb_2d.setCurrentText(str(self.args["网格类型"]))
        else:
            QMessageBox.warning(self, "输入错误", "请填写网格类型字段！")
            return
        
        if "角度容差" in self.args:
            self.sb_angle.setValue(float(self.args["角度容差"]))
        else:
            QMessageBox.warning(self, "输入错误", "请填写角度容差字段！")
            return
        
        if "曲率自适应" in self.args:
            self.sb_auto.setValue(int(self.args["曲率自适应"]))
        else:
            QMessageBox.warning(self, "输入错误", "请填写曲率自适应字段！")
            return
        
        if "二阶网格" in self.args:
            self.cb_high.setChecked(True) if 1 == int(self.args["二阶网格"]) else self.cb_high.setChecked(False)
        else:
            QMessageBox.warning(self, "输入错误", "请填写二阶网格字段！")
            return

    def on_select_clicked(self):
        sel = self.NCTI.SelectionManager(self.doc)
        count = len(sel.ObjectNames)
        self.lb_count.setText(str(count))

    def on_ok_clicked(self):
        if int(self.lb_count.text()) > 0:
            sel = self.NCTI.SelectionManager(self.doc)
            if len(sel.ObjectNames) > 0:
                meshType = 0
                meshTypeStr = self.cb_2d.currentText()
                if meshTypeStr == "混合四边形": meshType = 1
                if meshTypeStr == "全四边形": meshType = 2
                dbmeshSize = float(self.le_size.text())
                dbangleTol = self.sb_angle.value()
                intautoCurl = self.sb_auto.value()
                if self.cb_high.isChecked():
                    intHigh = 1
                else:
                    intHigh = 0

                if self.args["网格命令"] == "体网格":
                    meshCmd = "cmd_ncti_create_volume_mesh"
                elif self.args["网格命令"] == "面网格":
                    meshCmd = "cmd_ncti_create_surface_mesh"
                else:
                    return
                meshNames = ["mesh_" + obj for obj in sel.ObjectNames]
                self.doc.RunCommand(meshCmd, sel.ObjectNames, meshNames, {"MeshSize":dbmeshSize,"MeshType":meshType,"AngleTol":dbangleTol,"AutoCurvature":intautoCurl,"HighOrder":intHigh})
                # self.accept()
                self.close()
        else:
            QMessageBox.warning(self, "提示", "请先选择对象")
    
    def on_cancel_clicked(self):
        # self.reject()
        self.close() 

    def closeEvent(self, event):
        self.closePreview.emit()  # 发射关闭信号
        super().closeEvent(event)

def MeshDialog(*arg):
    window = MeshSettingView(*arg) 
    preview = PreviewLabel(window)
    window.installEventFilter(preview)
    preview.show()
    window.show()
    if window.exec_() == QDialog.Accepted:
        print(print("网格设置：设置成功"))
    return ()